package com.cheng.chat;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class TalkReceive implements Runnable{
    DatagramSocket socket =null;


    private int port;
    private String msgSend;

    public TalkReceive(int port,String msgSend) {
        this.port = port;
        this.msgSend = msgSend;

        try {
            socket = new DatagramSocket(port);//建立socket连接
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while(true) {  //循环接收
            try {
                byte[] bytes = new byte[1024];//缓冲区存放数据
                DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);//把数据返回成数据包
                socket.receive(packet);//socket阻塞式接收包裹
                //断开连接请求
                byte[] data = packet.getData();
                String receivedate = new String(data, 0, data.length);
                System.out.println(msgSend + ": " + receivedate);
                if (receivedate.equals("再见")) {
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        socket.close();
    }
}
